package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import com.thuan.hibernate.Repository;

import pojo.League;
import pojo.Reward;
import server.Server;
import util.Utils;

public class LeagueManageView extends ChessOnlineView implements ActionListener, MouseListener{
	private static final long serialVersionUID = -7683061137901277552L;
	
	private JTextField txtId, txtName, txtEndDate,  txtStartDate;
	private static JComboBox<Reward> cbReward;
	
	public LeagueManageView(Server mainScreen) {
		super(mainScreen);
	}
	
	@Override
	public void lockText(boolean status)
	{
		txtId.setEnabled(false);
		txtName.setEnabled(!status);
		txtStartDate.setEnabled(!status);
		txtEndDate.setEnabled(!status);
	}

	@Override
	public void doAdd(){
		super.doAdd();
		
		txtId.setText("");
		txtName.setText("");
		txtStartDate.setText("");
		txtEndDate.setText("");
	}
	
	@Override
	public void doSave(){			
		String id = txtId.getText();
		String name = txtName.getText();
		Reward reward = null;
		if(cbReward.getSelectedItem() != null)
			reward = (Reward) cbReward.getSelectedItem();
		String strStartDate = txtStartDate.getText();
		String strEndDate = txtEndDate.getText();

		if(name.equals("")) {
			JOptionPane.showMessageDialog(null, "Please enter League Name.");
			txtName.requestFocus();
			return;
		}
		
		if(reward == null) {
			JOptionPane.showMessageDialog(null, "Please choose Reward.");
			return;
		}
		
		if(strStartDate.equals("")) {
			JOptionPane.showMessageDialog(null, "Please enter Start Date (Format: " + dateFormat + ").");
			txtStartDate.selectAll();
			txtStartDate.requestFocus();
			return;
		}
		
		if(!Utils.isThisDateValid(strStartDate, dateFormat)){
			JOptionPane.showMessageDialog(null, "Invalid Start Date format (Format: " + dateFormat + ").");
			txtStartDate.selectAll();
			txtStartDate.requestFocus();
			return;
		}
		
		if(strEndDate.equals("")) {
			JOptionPane.showMessageDialog(null, "Please enter End Date (Format: " + dateFormat + ").");
			txtEndDate.requestFocus();
			return;
		}
		
		if(!Utils.isThisDateValid(strEndDate, dateFormat)){
			JOptionPane.showMessageDialog(null, "Invalid End Date format (Format: " + dateFormat + ").");
			txtEndDate.selectAll();
			txtEndDate.requestFocus();
			return;
		}
		
		try {
			int rs = Utils.compareDates(strStartDate, strEndDate, dateFormat);
			
			if(rs > 0 || rs == 0){
				JOptionPane.showMessageDialog(null, "Start Date is not after than or equal End Date.");
				txtStartDate.selectAll();
				txtStartDate.requestFocus();
				return;	
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			Date startDate = sdf.parse(strStartDate);
	    	Date endDate = sdf.parse(strEndDate);
	    	
			if (btnUpdate.getText().equalsIgnoreCase("Update"))
				Repository.updateLeague(Integer.parseInt(id), name, reward, startDate, endDate);
			else
				Repository.addLeague(name, startDate, endDate, reward.getRewardId());
			
			super.doSave();

		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	@Override
	public void addControl()
	{
		JPanel pnInfo = new JPanel();
		pnInfo.setLayout(new BorderLayout());
		JPanel pnTitle = new JPanel();
		JLabel lblTitle = new JLabel("League Manage");
		lblTitle.setFont(new Font("arial", Font.BOLD, 22));
		lblTitle.setForeground(Color.BLUE);
		pnTitle.add(lblTitle);
		pnInfo.add(pnUserInfo, BorderLayout.EAST);
		pnInfo.add(pnTitle, BorderLayout.SOUTH);
		pnInfo.setBorder(new EmptyBorder(0, 0, 10, 0));
		this.add(pnInfo,BorderLayout.NORTH);

		JPanel pnDetail = new JPanel();
		pnDetail.setLayout(new BorderLayout());

		JPanel pnCenter = new JPanel();
		pnCenter.setLayout(new BoxLayout(pnCenter, BoxLayout.Y_AXIS));	

		Vector<String> colNames = new Vector<String>( Arrays.asList( 
				new String[]{ "Id", "Name", "Reward", "Start Date", "End Date", })); 
		dftMolde = new DefaultTableModel(colNames, 0){
			private static final long serialVersionUID = -2941343871925263336L;
			@Override
		    public boolean isCellEditable(int row, int column) {
		       return false;
		    }
		};
		jtable = new JTable(dftMolde);
		jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane jsp = new JScrollPane(jtable);
		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		jsp.setPreferredSize(new Dimension(0, 200));

		jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {	
				if (!e.getValueIsAdjusting()) {
					int Index = jtable.getSelectedRow();
					if (Index == -1) {
						return;
					}

					int leagueId = Integer.parseInt(jtable.getValueAt(Index, 0).toString());				
					DateFormat sdf = new SimpleDateFormat(dateFormat);
					
					League league = Repository.findLeague(leagueId);
					txtId.setText(Integer.toString(league.getLeagueId()));
					txtName.setText(league.getName());
					cbReward.getModel().setSelectedItem(league.getReward());
					txtStartDate.setText(sdf.format(league.getStartDate()));
					txtEndDate.setText(sdf.format(league.getEndDate()));

					btnNew.setText("Cancel");
					btnUpdate.setText("Update");
					btnUpdate.setEnabled(true);
					txtName.setEnabled(true);
					txtStartDate.setEnabled(true);
					txtEndDate.setEnabled(true);
				}
			}
		});
		pnCenter.add(jsp);

		JPanel pnId = new JPanel();
		JLabel lblId = new JLabel("League Id:");
		txtId = new JTextField(20);			
		pnId.add(lblId);
		pnId.add(txtId);		
		pnId.setBorder(new EmptyBorder(10, 0, 0, 0));
		
		JPanel pnName = new JPanel();
		JLabel lblName = new JLabel("League Name:          ");
		txtName = new JTextField(20);			
		pnName.add(lblName);
		pnName.add(txtName);		

		JPanel pnReward = new JPanel();
		JLabel lblReward = new JLabel("Reward:");

		cbReward = new JComboBox<Reward>();	
		cbReward.setPreferredSize(new Dimension(220, 20));	

		pnReward.add(lblReward);
		pnReward.add(cbReward);		
		
		JPanel pnStartDate = new JPanel();
		JLabel lblStartDate = new JLabel("Start Date:");
		txtStartDate = new JTextField(20);			
		pnStartDate.add(lblStartDate);
		pnStartDate.add(txtStartDate);		

		JPanel pnEndDate = new JPanel();
		JLabel lblEndDate = new JLabel("End Date:");
		txtEndDate = new JTextField(20);			
		pnEndDate.add(lblEndDate);
		pnEndDate.add(txtEndDate);		

		lblId.setPreferredSize(lblName.getPreferredSize());
		lblName.setPreferredSize(lblName.getPreferredSize());
		lblReward.setPreferredSize(lblName.getPreferredSize());
		lblStartDate.setPreferredSize(lblName.getPreferredSize());
		lblEndDate.setPreferredSize(lblName.getPreferredSize());

		lockText(true);

		pnCenter.add(pnId);
		pnCenter.add(pnName);
		pnCenter.add(pnReward);
		pnCenter.add(pnStartDate);
		pnCenter.add(pnEndDate);

		JPanel pnButton = new JPanel();
		btnNew = new JButton("New");
		btnNew.setCursor(new Cursor(Cursor.HAND_CURSOR));

		btnUpdate = new JButton("Save");
		btnUpdate.setCursor(new Cursor(Cursor.HAND_CURSOR));
		/*this.getRootPane().setDefaultButton(btnUpdate);*/

		btnDelete = new JButton("Delete");
		btnDelete.setCursor(new Cursor(Cursor.HAND_CURSOR));

		btnUpdate.setEnabled(false);

		pnButton.add(btnNew);
		pnButton.add(btnUpdate);
		pnButton.add(btnDelete);	
		pnDetail.add(pnButton, BorderLayout.SOUTH);

		pnDetail.add(pnCenter, BorderLayout.CENTER);

		this.add(pnDetail, BorderLayout.CENTER);
		
		JPanel pnSouth = new JPanel();
		pnSouth.setPreferredSize(new Dimension(0, 10));
		this.add(pnSouth, BorderLayout.SOUTH);
		
		mMainScreen.frame.getContentPane().add(this);
	}
	
	@Override
	public void getAll()
	{
		DateFormat sdf = new SimpleDateFormat(dateFormat);
		List<League> leagues = Repository.listLeagues();
		dftMolde.setRowCount(0);
		for(League i : leagues){
			Vector<String> vector = new Vector<String>();
			vector.add(Integer.toString(i.getLeagueId()));
			vector.add(i.getName());
			vector.add(i.getReward().getName());
			vector.add(sdf.format(i.getStartDate()));
			vector.add(sdf.format(i.getEndDate()));
			dftMolde.addRow(vector);		
		}
	}
	
	@Override
	public void getAllDataBase()
	{		
		List<Reward> rewards = Repository.listRewards();
		cbReward.removeAllItems();
		
		for(Reward i : rewards){
			cbReward.addItem(i);
		}
	}
	
	@Override
	public void addEvents()
	{
		super.addEvents();
	}
	
	@Override
	public void clearText()
	{		
		txtId.setText("");
		txtName.setText("");
		txtStartDate.setText("");
		txtEndDate.setText("");
	}
	
	@Override
	public void doDelete()
	{		
		if (dftMolde.getRowCount() == 0) {
			JOptionPane.showMessageDialog(null, "Empty league");
			return;							
		}
		if (jtable.getSelectedRowCount() == 0) {
			JOptionPane.showMessageDialog(null, "Please choose league to delete");
			return;							
		}
		String id = (String) jtable.getModel().getValueAt(jtable.getSelectedRow(), 0);
		int chooseAnswer = JOptionPane.showConfirmDialog(null, "Do you really want to delete [League Id: "
				+ id + "]?", "Confirm", JOptionPane.YES_NO_OPTION);
		
		if(chooseAnswer == JOptionPane.YES_OPTION){
			if(Repository.deleteLeague(Integer.parseInt(id)))
				JOptionPane.showMessageDialog(null, "Completely delete [League Id: "+ id +"].");	
			getAll();			
		}
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
